/***************************************************
> Copyright (C) 2024 ==KINGYI== All rights reserved.
> File Name: 1.c
> Author:cjy
> Mail: 
> Created Time: 2024年08月08日 星期四 11时02分32秒
***************************************************/
// 设计一个抢票系统，总共有100张票，有四个窗口可以同时卖票
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
pthread_mutex_t mutex;
int data = 20;
void*fun1(void *arg){
	int i = 0;
	while(data > 0){
	pthread_mutex_lock(&mutex);
	data--;
	i++;
	printf("fun1:%d\n",data);
	pthread_mutex_unlock(&mutex);
	sleep(1);
	}
printf("票卖完了%d\n",i);
}
void*fun2(void *arg){
	int i = 0;
	while(data > 0){
	pthread_mutex_lock(&mutex);
	data--;
	i++;
	printf("fun2:%d\n",data);
	pthread_mutex_unlock(&mutex);
	sleep(1);
	}
printf("票卖完了%d\n",i);
}

void*fun3(void *arg){
	int i = 0;
	while(data > 0){
	pthread_mutex_lock(&mutex);
	data--;
	i++;
	printf("fun3:%d\n",data);
	pthread_mutex_unlock(&mutex);
	sleep(1);
	}
printf("票卖完了%d\n",i);
}
void*fun4(void *arg){
	int i = 0;
	while(data > 0){
	pthread_mutex_lock(&mutex);
	data--;
	i++;
	printf("fun4:%d\n",data);
	pthread_mutex_unlock(&mutex);
	sleep(1);
	}
printf("票卖完了%d\n",i);
}
int main(int argc,const char* argv[])
{
	pthread_t tid1 = 0,tid2 = 0,tid3 = 0,tid4 = 0;
	int ret = 0;
	pthread_mutex_init(&mutex,NULL);
	ret = pthread_create(&tid1,NULL,fun1,NULL);
	if(ret != 0)
	{
		perror("pthread_create");
		exit(-1);
	}
	ret = pthread_create(&tid2,NULL,fun2,NULL);
	if(ret != 0)
	{
		perror("pthread_create");
		exit(-1);
	}
	ret = pthread_create(&tid3,NULL,fun3,NULL);
	if(ret != 0)
	{
		perror("pthread_create");
		exit(-1);
	}
	ret = pthread_create(&tid4,NULL,fun4,NULL);
	if(ret != 0)
	{
		perror("pthread_create");
		exit(-1);
	}
	pthread_join(tid1,NULL);
	pthread_join(tid2,NULL);
	pthread_join(tid3,NULL);
	pthread_join(tid4,NULL);
	pthread_mutex_destroy(&mutex);
	
    return 0;
}
